package com.samsung.sbackup;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.samsung.adapter.CustomDrawerAdapter;
import com.samsung.item.DrawerItem;

public class MainActivity extends FragmentActivity {

	boolean doubleBackToExitPressedOnce = false;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	SharedPreferences sharedPref;
	SharedPreferences.Editor prefEditor;
	public static String PREFS_NOT_SETUP = "haven't set up prefs";

	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	CustomDrawerAdapter adapter;

	List<DrawerItem> dataList;
	private int mSelectedPostion;

	private static final String SELECTED_POSITION = "selectedPosition";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		sharedPref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		prefEditor = sharedPref.edit();

		if (sharedPref.getString(FragmentSettingsPreference.MAX_BACKUPS,
				PREFS_NOT_SETUP).equals(PREFS_NOT_SETUP))
			initDefaultPreferences();

		createFolder(sharedPref.getString(
				FragmentSettingsPreference.BACKUP_PATH, "/"), this);

		// validate max backups condition
		QuickBackup.MaxBackupsChecker("None", Integer.parseInt(sharedPref
				.getString(FragmentSettingsPreference.MAX_BACKUPS, "5")),
				sharedPref.getString(FragmentSettingsPreference.BACKUP_PATH,
						"/"));

		// Initializing
		dataList = new ArrayList<DrawerItem>();
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		// Set shadow to the right of drawer
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);

		// Add Drawer Item to dataList
		dataList.add(new DrawerItem("Home screen", R.drawable.ic_home));
		dataList.add(new DrawerItem("Apps backup", R.drawable.ic_apps));
		dataList.add(new DrawerItem("Manage backups",
				R.drawable.ic_manage_backups));
		dataList.add(new DrawerItem("Settings", R.drawable.ic_settings));
		dataList.add(new DrawerItem("About", R.drawable.ic_about));
		dataList.add(new DrawerItem("Exit", R.drawable.ic_exit));

		adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
				dataList);

		mDrawerList.setAdapter(adapter);

		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};

		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			SelectItem(0);
		} else {
			mSelectedPostion = savedInstanceState.getInt(SELECTED_POSITION);
			SelectItem(mSelectedPostion);
		}
	}

	public void SelectItem(int position) {

		Fragment fragment = null;
		Bundle args = new Bundle();
		switch (position) {
		case 0:
			fragment = new FragmentHomeScreen();
			break;
		case 1:
			Intent i = new Intent(getApplicationContext(),
					FragmentAppsBackup.class);
			startActivity(i);
			mDrawerLayout.closeDrawer(mDrawerList);
			break;
		case 2:
			fragment = new FragmentManageBackups();
			break;
		case 3:
			fragment = new FragmentSettingsPreference();
			break;
		case 4:
			fragment = new FragmentAbout();
			break;
		case 5: {
			AlertDialog dialog;
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);
			builder.setTitle("Are you sure you want to exit?");
			builder.setNegativeButton("Cancel", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					mDrawerLayout.closeDrawer(mDrawerList);
				}
			});
			builder.setPositiveButton("Ok", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			dialog = builder.create();
			dialog.show();
		}
			break;
		default:
			break;
		}

		if (fragment != null && position != 5 && position != 1) {
			fragment.setArguments(args);
			FragmentManager frgManager = getFragmentManager();
			FragmentTransaction frgTransaction = frgManager.beginTransaction();
			frgTransaction.replace(R.id.content_frame, fragment).commit();

			mDrawerList.setItemChecked(position, true);
			setTitle(dataList.get(position).getItemName());
			mDrawerLayout.closeDrawer(mDrawerList);
		} 
		else
			mDrawerList.setItemChecked(mSelectedPostion, true);
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggles
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		return false;
	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (position != 5 && position != 1)
				mSelectedPostion = position;
			SelectItem(position);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(SELECTED_POSITION, mSelectedPostion);
	}

	@Override
	public void onBackPressed() {
		if (mSelectedPostion == 0) {
			if (doubleBackToExitPressedOnce) {
				super.onBackPressed();
				return;
			}

			this.doubleBackToExitPressedOnce = true;
			Toast.makeText(this, "Please click BACK again to exit",
					Toast.LENGTH_SHORT).show();

			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					doubleBackToExitPressedOnce = false;
				}
			}, 3000);
		} else {
			mSelectedPostion = 0;
			SelectItem(0);
		}
	}

	/**
	 * Init preferences for the 1st time application installed
	 */
	private void initDefaultPreferences() {

		// init backup path
		String storage[] = FragmentSettingsPreference.getStorageDirectories();

		if (new File(String.valueOf(storage[0])).list() != null)
			prefEditor.putString(FragmentSettingsPreference.BACKUP_PATH,
					storage[0] + "/Android/data/" + getPackageName()
							+ "/files/Download");
		else if (new File(String.valueOf(storage[1])).list() != null)
			prefEditor.putString(FragmentSettingsPreference.BACKUP_PATH,
					storage[1] + "/Android/data/" + getPackageName()
							+ "/files/Download");

		// init max backup files
		prefEditor.putString(FragmentSettingsPreference.MAX_BACKUPS, "5");

		// init schedule backup
		prefEditor
				.putBoolean(FragmentSettingsPreference.SCHEDULE_BACKUP, false);

		// commit the last time
		prefEditor.commit();
	}

	/**
	 * Create the folder to store the backups
	 * 
	 * @param path
	 *            Path to the folder
	 */
	@TargetApi(19)
	public static void createFolder(String path, Context ctx) {
		File folder = new File(path);
		if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT) {
			// create backup folders (both internal and external)
			if (!folder.exists()) {
				ctx.getExternalFilesDirs(Environment.DIRECTORY_DOWNLOADS);
			}
		} else {
			if (!folder.exists()) {
				boolean success = true;
				success = folder.mkdirs();
				if (success) {
					Toast.makeText(ctx, "Created folder " + path,
							Toast.LENGTH_SHORT).show();
				} else {
					System.out.println("Failed to create SBACKUP folder");
				}
			} else
				System.out.println("Folder existed");
		}
	}
}
